#include "authoritymanager.h"
#include <QRegularExpression>
#include <QTextStream>
#include <QFile>
#include <QDebug>
#include <QCoreApplication>
AuthorityManager::AuthorityManager()
{
	m_level = AuthorityManager::AUTH_USER;
}

AuthorityManager::AUTH_LEVEL AuthorityManager::getCurrentLevel()
{
	// aes_init(3);
	if (m_level == AuthorityManager::AUTH_USER)
		return m_level;
	else {
		QDateTime time = QDateTime::currentDateTime();
		if (time < m_time.addSecs(300))
		{
			return m_level;
		}
		else {
			return AuthorityManager::AUTH_USER;
		}
	}
}

bool AuthorityManager::checkUserPwd(QString user, QString pwd)
{
	QString path = QString("%1/Config/pwd.cfg").arg(QCoreApplication::applicationDirPath());
	QMap<QString, QString> mapUP = parsePasswordConfig(path);
	QString pwdInFile = mapUP[user.toLower()];
	bool bRet = false;
	if (mapUP.count() == 0 || pwdInFile.isEmpty())
	{
		if (user.toLower() == "blq" && pwd == "2019")
		{
			m_level = AuthorityManager::AUTH_RD;
			bRet = true;
			m_time = QDateTime::currentDateTime();
		}
		else if (user.toLower() == "admin" && pwd == "20192019")
		{
			m_level = AuthorityManager::AUTH_ADMIN;
			bRet = true;
			m_time = QDateTime::currentDateTime();
		}
	}
	else
	{
		if (user.toLower() == "blq" && pwd == pwdInFile)
		{
			m_level = AuthorityManager::AUTH_RD;
			bRet = true;
			m_time = QDateTime::currentDateTime();
		}
		else if (user.toLower() == "admin" && pwd == pwdInFile)
		{
			m_level = AuthorityManager::AUTH_ADMIN;
			bRet = true;
			m_time = QDateTime::currentDateTime();
		}

	}
	return bRet;
}

QMap<QString, QString> AuthorityManager::parsePasswordConfig(const QString &filePath)
{
	QMap<QString, QString> credentials;
	QFile file(filePath);

	if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
		qDebug() << "can't open :" << filePath;
		return credentials;
	}

	QTextStream in(&file);
	QString allText = in.readAll();
	file.close();

	QRegularExpression re("(\\w+)\\s*=\\s*(\\S+)");
	QRegularExpressionMatchIterator i = re.globalMatch(allText);

	while (i.hasNext()) {
		QRegularExpressionMatch match = i.next();
		if (match.hasMatch()) {
			QString username = match.captured(1);
			QString password = match.captured(2);
			credentials.insert(username.toLower(), password);
		}
	}

	return credentials;
}